<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
  <!-- 父组件定义函数给子组件，子组件用父组件的函数函数传递数据给父组件-->
        <my-header @addTodo="addTodo"/>
        <my-list :todos="todos" :deleteObj="deleteObj" :checkTodo="checkTodo"/>
        <my-footer :todos="todos" @clearSelect="clearSelect" @checkAllTodo="checkAllTodo"/>
      </div>
    </div>
  </div>

</template>

<script>
import MyHeader from "./components/MyHeader";
import MyList from "./components/MyList";
import MyFooter from "./components/MyFooter";
export default {
  name: 'App',
  components: {
    MyHeader,
    MyList,
    MyFooter
  },
  data(){
    return{
      //由于todos是MyHeader组件和MyFooter组件都在使用，所以放在APP中（状态提升）
      //初始化浏览器的时候 将浏览器本地的数据接收解析渲染到todolist当中
      todos:JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods:{
    //父组件定义一个函数给子组件
    addTodo(data){
      this.todos.push(data);
    },
    //勾选or取消勾选一个todo
    checkTodo(id){
      this.todos.forEach((todo)=>{
        if(todo.id===id) todo.done = !todo.done
      })
    },
    //删除列表中的指定元素
    deleteObj(id,done){
      if(!done)  return alert('请先选中再进行删除!')
      //如果id不能全等于当前对象中的id 则过滤掉
      this.todos = this.todos.filter((todo) => {
        return todo.id !== id
      })
    },
    checkAllTodo(done){
      this.todos.forEach((todo) => {
        todo.done = done
      })
    },
    clearSelect(){
     // 过滤器 将done不为true 过滤掉，然后返回到当前app中
     this.todos = this.todos.filter((todo) => {
        return ! todo.done
      })
    }
  }
  ,
  watch :{
    todos: {
      deep:true,
      //当值发生改变的时候，将添加的数据存储到本地浏览器中 存储的时候将数据按照json格式存储
      handler(value) {
        localStorage.setItem('todos', JSON.stringify(value))
      }
    }
  },
}
</script>

<style scoped>
/*base*/
body {
  background: #fff;
}


.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
